/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.opencfg.core.mode.reactor;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.Socket;
import java.util.concurrent.atomic.AtomicInteger;

public class Atom implements Runnable {

	public static final AtomicInteger counter = new AtomicInteger(0);

	private volatile boolean flug = true;

	DataOutputStream out = null;
	DataInputStream in = null;

	Socket socket = null;

	@Override
	public void run() {
		while (flug) {
			try {
				socket = new Socket("127.0.0.1", 5555);
				socket.setSoTimeout(10000);
				out = new DataOutputStream((socket.getOutputStream()));
				String query = "Hello;";
				byte[] request = query.getBytes();
				out.write(request);
				out.flush();

				socket.shutdownOutput();

				in = new DataInputStream(socket.getInputStream());
				byte[] reply = new byte[40];
				in.read(reply);
				in.close();
				out.close();

				counter.incrementAndGet();
			} catch (Exception e) {
				e.printStackTrace();
			} finally {
				try {
					out.close();
				} catch (IOException e) {
				}
			}
		}
	}

	public static void main(String[] args) throws Exception {
		int joinTime = 5000;
		int atomsCount = 2;
		Atom[] atomArray = new Atom[atomsCount];
		Thread[] threadArray = new Thread[atomsCount];
		for (int i = 0; i < atomsCount - 1; i++) {
			atomArray[i] = new Atom();
			threadArray[i] = new Thread(atomArray[i]);
			threadArray[i].start();
		}
		Thread.currentThread().join(joinTime);
		for (int i = 0; i < atomsCount - 1; i++) {
			atomArray[i].flug = false;
		}
		int total = counter.get();
		System.out.println("Time " + joinTime + "ms, process " + total + " request, avg " + (double)total / (double)(joinTime/1000) );
	}

}
